import React, { useContext } from "react";
import NestList from './Nest';
import DataTool from './DataTool';
import {LedgerContext, LedgerProvider} from './Ledger';
import BookManager from './BookManager';

import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';

const Table = ({desc, descAddi, name, data, error, cols, editable, dataToolButtonElems, dataToolForms}) => {

  const content = error 
    ? <div style={{padding: '10px'}}>
        <div className='bad-icon' />
        {data.map(msg => <pre>{msg}</pre>)}
      </div>
    : <NestList {...{data, cols, editable}} />

  return <div style={{height: '100%', width: '100%', display:'flex', flexDirection:'column', position: 'asbolute'}}>
    <div className='title'>
      <div className="title-primary">{desc}</div>
      <div className="title-subsidary">{descAddi ?? name}</div>
    </div>
    <div className="tool-button-bar">
      {dataToolButtonElems}
    </div>
    {dataToolForms}
    {content}
  </div>
}

const Page = () => {

  const {currBook} = useContext(LedgerContext);
    
  const dataToolButtonElems = [];
  const dataToolForms = [];
  for (let [toolName, toolComp] of Object.entries(DataTool)){

    let toolArgs = currBook.dataTool.hasOwnProperty(toolName)
      ? {...currBook.dataTool[toolName], tableName: currBook.name}
      : {hidden: true};
  
    const [button, elem] = toolComp(toolArgs);
    dataToolButtonElems.push(button);
    dataToolForms.push(elem);
  }

  return <div style={{height: '100vh', display:'flex', overflow:'hidden'}}>
    <BookManager />
    <Table {...{...currBook, dataToolButtonElems, dataToolForms}} />
  </div>

}


const App = () => {

  return <LedgerProvider>
    <Page />
  </LedgerProvider>
};

export default App;